<template>
  <el-dialog append-to-body :title="textMap[dialogStatus]" :visible.sync="dialogVisible" @close="handleClose">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="ticketForm"
      label-position="left"
      label-width="100px"
      append-to-body
      style="margin-left:50px;"
    >
      <el-form-item label="工单名称" prop="name">
        <el-input v-model="ticketForm.name" placeholder="请输入工单名称" />
        <div v-if="titleTemplate" class="title-template-hint">
          <el-tag type="info" size="mini">建议标题：{{ titleTemplate }}</el-tag>
          <el-button type="text" size="mini" @click="applyTitleTemplate">应用模板</el-button>
        </div>
      </el-form-item>
      <el-form-item label="关联订单" prop="crmorder_id">
        <el-select
          v-model="ticketForm.crmorder_id"
          filterable
          remote
          reserve-keyword
          placeholder="请输入订单名称或编号搜索"
          :remote-method="remoteSearchOrders"
          :loading="ordersLoading"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in orderOptions"
            :key="item.id"
            :label="item.name ? `${item.name} (${item.order_no})` : item.order_no"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="assignee_id">
        <el-select
          v-model="ticketForm.assignee_id"
          filterable
          remote
          reserve-keyword
          placeholder="请输入负责人姓名搜索"
          :remote-method="remoteSearchUsers"
          :loading="usersLoading"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="item.show_name || item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="ticketForm.status" placeholder="请选择状态">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="ticketForm.priority" placeholder="请选择优先级" @change="onPriorityChange">
          <el-option label="普通" :value="0" />
          <el-option label="紧急" :value="1" />
          <el-option label="特急" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="截止时间" prop="end_at">
        <el-date-picker
          v-model="ticketForm.end_at"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="初始消息" prop="comment">
        <tiptap-editor
          v-if="dialogVisible"
          ref="tiptapEditor"
          :key="'tiptap-' + dialogStatus"
          v-model="ticketForm.comment"
          :height="editorHeight"
          :menubar="editorMenubar"
        />
      </el-form-item>
      <!-- 文件附件 -->
      <el-form-item label="附件" class="compact-form-item">
        <!-- 展示已选择的文件 -->
        <div v-if="ticketForm.crmfiles && ticketForm.crmfiles.length > 0" class="file-list-compact">
          <div v-for="(item, index) in ticketForm.crmfiles" :key="index" class="file-item-compact">
            <span class="file-name-compact">{{ item.filename }}</span>
            <i class="el-icon-close" @click="removeFile(index)" />
          </div>
        </div>
        <!-- 文件管理器组件 -->
        <crmfilesmanager color="#1890ff" class="editor-upload-btn" @insert="handleInsertFile" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="submitForm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Post, Put, GetStatusOptions } from '@/api/crm/ticket'
import { Get as GetOrders } from '@/api/crm/crmorder'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import Crmfilesmanager from '@/components/crmfilesmanager'
import TiptapEditor from '@/components/Tiptap'

export default {
  name: 'CrmTicketForm',
  components: {
    Crmfilesmanager,
    TiptapEditor
  },
  props: {
    // 控制对话框是否显示
    visible: {
      type: Boolean,
      default: false
    },
    // 对话框状态: create-创建, update-更新
    status: {
      type: String,
      default: 'create'
    },
    // 编辑时的工单数据
    ticketData: {
      type: Object,
      default: () => ({})
    },
    // 默认关联的订单ID
    defaultOrderId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogStatus: 'create',
      textMap: {
        create: '创建工单',
        update: '编辑工单'
      },
      submitting: false,

      // 工单表单
      ticketForm: {
        id: undefined,
        name: '',
        comment: '',
        status: 'open',
        crmorder_id: undefined,
        assignee_id: undefined,
        priority: 0,
        end_at: null,
        crmfiles: []
      },

      // 标题模板相关
      titleTemplate: '',
      currentOrderInfo: null,

      // 表单验证规则
      rules: {
        name: [{ required: true, message: '工单名称不能为空', trigger: 'blur' }],
        comment: [{ required: true, message: '初始消息内容不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        assignee_id: [{ required: true, message: '请选择负责人', trigger: 'change' }]
      },

      // 状态选项
      statusOptions: [
        { value: 'open', label: '开启' },
        { value: 'hold', label: '暂停' },
        { value: 'close', label: '关闭' }
      ],

      // 选项数据
      orderOptions: [], // 订单选项
      userOptions: [], // 用户选项
      ordersLoading: false, // 订单加载状态
      usersLoading: false, // 用户加载状态

      // Editor config
      editorHeight: 120,
      editorMenubar: true
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.dialogVisible = val
        if (val) {
          this.init()
        }
      },
      immediate: true
    },
    // 监听订单选择变化，更新标题模板
    'ticketForm.crmorder_id': {
      handler(val) {
        if (val && this.dialogStatus === 'create') {
          this.getOrderInfo(val)
        }
      }
    },
    dialogVisible: {
      handler(val) {
        this.$emit('update:visible', val)
      }
    },
    status: {
      handler(val) {
        this.dialogStatus = val
      },
      immediate: true
    },
    ticketData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.initFormData(val)
        }
      },
      immediate: true,
      deep: true
    },
    defaultOrderId: {
      handler(val) {
        if (val && this.dialogStatus === 'create') {
          this.ticketForm.crmorder_id = val
          // 获取订单信息
          this.getOrderInfo(val)
        }
      },
      immediate: true
    }
  },
  created() {
    // 获取状态选项
    this.getStatusOptions()
    // 获取用户选项
    this.getUserOptions()
  },
  beforeDestroy() {
    // Tiptap 编辑器会自动清理，无需手动销毁
  },
  methods: {
    // 初始化
    init() {
      if (this.dialogStatus === 'create') {
        this.resetForm()
        if (this.defaultOrderId) {
          this.ticketForm.crmorder_id = this.defaultOrderId
          this.getOrderInfo(this.defaultOrderId)
        } else {
          // 如果没有默认订单，仍然设置默认截止时间
          this.setDefaultDeadline(0)
        }
      } else {
        this.initFormData(this.ticketData)
      }

      this.$nextTick(() => {
        if (this.$refs.dataForm) {
          this.$refs.dataForm.clearValidate()
        }
        // Tiptap 编辑器会自动初始化
      })
    },

    // 初始化表单数据
    initFormData(data) {
      this.ticketForm = {
        id: data.id,
        name: data.name || '',
        comment: '',
        status: data.status || 'open',
        crmorder_id: data.crmorder_id,
        assignee_id: data.assignee_id,
        priority: data.priority !== undefined ? data.priority : 0,
        end_at: data.end_at || null,
        crmfiles: []
      }
    },

    // 重置表单
    resetForm() {
      this.ticketForm = {
        id: undefined,
        name: '',
        comment: '',
        status: 'open',
        crmorder_id: this.defaultOrderId || undefined,
        assignee_id: undefined,
        priority: 0,
        end_at: null,
        crmfiles: []
      }
      this.titleTemplate = ''
      this.currentOrderInfo = null
      // 设置默认截止时间（普通优先级默认7天）
      this.setDefaultDeadline(0)
    },

    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      this.$emit('close')
    },

    // 获取订单信息
    getOrderInfo(orderId) {
      if (!orderId) return

      this.ordersLoading = true
      GetOrders(orderId)
        .then(response => {
          if (response.data) {
            const order = response.data
            this.currentOrderInfo = order

            // 添加到订单选项中
            if (this.orderOptions.findIndex(item => item.id === order.id) === -1) {
              this.orderOptions.push(order)
            }

            // 生成标题模板
            this.generateTitleTemplate()
          }
        })
        .catch(error => {
          console.error('获取订单信息失败:', error)
        })
        .finally(() => {
          this.ordersLoading = false
        })
    },

    // 获取工单状态选项
    getStatusOptions() {
      GetStatusOptions().then(response => {
        if (response.data && response.data.length > 0) {
          this.statusOptions = response.data
        }
      }).catch(error => {
        console.error('获取状态选项失败:', error)
      })
    },

    // 获取订单选项
    getOrderOptions(query) {
      this.ordersLoading = true
      const params = new URLSearchParams()
      params.append('pagesize', 20)
      params.append('page', 1)
      if (query) {
        params.append('kw', query)
      }

      GetOrders(null, params.toString()).then(response => {
        this.orderOptions = response.data.data
        this.ordersLoading = false
      }).catch(() => {
        this.ordersLoading = false
      })
    },

    // 获取用户选项
    getUserOptions(query) {
      this.usersLoading = true
      const params = new URLSearchParams()
      params.append('is_active', 1)
      params.append('pagesize', 20)
      params.append('page', 1)
      if (query) {
        params.append('kw', query)
      }

      GetUsers(null, params.toString()).then(response => {
        this.userOptions = response.data.data
        this.usersLoading = false
      }).catch(() => {
        this.usersLoading = false
      })
    },

    // 远程搜索订单
    remoteSearchOrders(query) {
      if (query) {
        this.getOrderOptions(query)
      } else {
        this.orderOptions = []
      }
    },

    // 远程搜索用户
    remoteSearchUsers(query) {
      if (query) {
        this.getUserOptions(query)
      } else {
        this.userOptions = []
      }
    },

    // 移除文件
    removeFile(index) {
      this.ticketForm.crmfiles.splice(index, 1)
    },

    // 从文件管理器插入文件
    handleInsertFile(item) {
      if (!this.ticketForm.crmfiles) {
        this.ticketForm.crmfiles = []
      }
      if (this.ticketForm.crmfiles.findIndex(file => file.id === item.id) === -1) {
        this.ticketForm.crmfiles.push(item)
      }
    },

    // 优先级变化处理
    onPriorityChange(priority) {
      // 设置对应的截止时间
      this.setDefaultDeadline(priority)
      // 更新标题模板
      this.generateTitleTemplate()
    },

    // 设置默认截止时间
    setDefaultDeadline(priority) {
      const now = new Date()
      let deadline

      if (priority === 2) {
        // 特急：当天晚上21:00
        deadline = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 21, 0, 0)
        // 如果当前时间已过21:00，设置为明天21:00
        if (now.getHours() >= 21) {
          deadline.setDate(deadline.getDate() + 1)
        }
      } else if (priority === 1) {
        // 紧急：48小时后
        deadline = new Date(now.getTime() + (48 * 60 * 60 * 1000))
      } else {
        // 普通：7天后
        deadline = new Date(now.getTime() + (7 * 24 * 60 * 60 * 1000))
      }

      const year = deadline.getFullYear()
      const month = String(deadline.getMonth() + 1).padStart(2, '0')
      const day = String(deadline.getDate()).padStart(2, '0')
      const hours = String(deadline.getHours()).padStart(2, '0')
      const minutes = String(deadline.getMinutes()).padStart(2, '0')
      const seconds = String(deadline.getSeconds()).padStart(2, '0')

      this.ticketForm.end_at = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 生成标题模板
    generateTitleTemplate() {
      if (!this.currentOrderInfo) {
        this.titleTemplate = ''
        return
      }

      const order = this.currentOrderInfo
      const priority = this.ticketForm.priority

      // 根据订单状态判断业务阶段
      let businessStage = '售中' // 默认售中
      if (order.state_name) {
        const stateName = order.state_name.toLowerCase()
        if (stateName.includes('报价') || stateName.includes('洽谈') || stateName.includes('跟进')) {
          businessStage = '售前'
        } else if (stateName.includes('完成') || stateName.includes('交付') || stateName.includes('验收')) {
          businessStage = '售后'
        }
      }

      // 构建标题模板
      let template = ''
      if (priority === 2) {
        template = `【特急】${businessStage}${order.name || order.order_no}工单-`
      } else if (priority === 1) {
        template = `【紧急】${businessStage}${order.name || order.order_no}工单-`
      } else {
        template = `${businessStage}${order.name || order.order_no}工单-`
      }

      this.titleTemplate = template
    },

    // 应用标题模板
    applyTitleTemplate() {
      if (this.titleTemplate) {
        this.ticketForm.name = this.titleTemplate
        this.titleTemplate = '' // 清空模板提示
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.submitting = true

          // 准备提交的数据
          const formData = {
            name: this.ticketForm.name,
            status: this.ticketForm.status,
            crmorder_id: this.ticketForm.crmorder_id,
            assignee_id: this.ticketForm.assignee_id,
            priority: this.ticketForm.priority,
            end_at: this.ticketForm.end_at,
            comment: this.ticketForm.comment,
            crmfiles: this.ticketForm.crmfiles
          }

          if (this.dialogStatus === 'update') {
            // 更新
            Put(this.ticketForm.id, formData).then(response => {
              this.submitting = false
              this.dialogVisible = false
              this.$notify({
                title: '成功',
                message: '更新工单成功',
                type: 'success',
                duration: 2000
              })
              this.$emit('success', response.data)
            }).catch(error => {
              this.submitting = false
              this.$notify({
                title: '失败',
                message: '更新工单失败: ' + (error.message || error),
                type: 'error',
                duration: 2000
              })
            })
          } else {
            // 创建
            Post(formData).then(response => {
              this.submitting = false
              this.dialogVisible = false
              this.$notify({
                title: '成功',
                message: '创建工单成功',
                type: 'success',
                duration: 2000
              })
              this.$emit('success', response.data)
            }).catch(error => {
              this.submitting = false
              this.$notify({
                title: '失败',
                message: '创建工单失败: ' + (error.message || error),
                type: 'error',
                duration: 2000
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.compact-form-item {
  margin-bottom: 8px;
}

.file-list-compact {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 8px;
}

.file-item-compact {
  display: inline-flex;
  align-items: center;
  background-color: #f0f9ff;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #d9ecff;
  font-size: 12px;
}

.file-name-compact {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-item-compact .el-icon-close {
  margin-left: 5px;
  cursor: pointer;
  color: #909399;
}

.file-item-compact .el-icon-close:hover {
  color: #F56C6C;
}

.editor-upload-btn {
  margin-top: 5px;
}

.title-template-hint {
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
